<template>
	<div class="bg">
		<el-card class="box-card">
			<div slot="header">
				<span>登录</span>
			</div>
			<el-form :model="form" :rules="rules" ref="form" status-icon label-width="60px">
				<el-form-item label="账号" prop="username">
					<el-input type="text" v-model="form.username" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input type="password" v-model="form.password" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button @click="handleLogin" type="primary">登录</el-button>
				</el-form-item>
			</el-form>
			<div>
				<router-link to="/register">注册账号</router-link>
				<router-link to="/" class="forget">忘记密码？</router-link>
			</div>
		</el-card>
	</div>
</template>

<script>
import { Admin } from '@/api';
import global from '@/plugins/global';

export default {
	data() {
		return {
			form: {
				username: 'admin',
				password: '123',
			},
			rules: {
				username: [
					{ required: true, message: '请输入账号名称', trigger: 'blur' },
					{ min: 3, max: 5, message: '账号长度在 3 到 5 个字符', trigger: 'blur' }
				],
				password: [
					{ required: true, message: '请输入密码', trigger: 'blur' },
					{ pattern: /^\d{3,}/, message: '密码至少3个数字', trigger: 'blur' }
				],
			}
		}
	},
	created() {
		document.title = "登录---CMS管理系统"
	},
	methods: {
		handleLogin() {
			//表单验证
			this.$refs.form.validate(async (valid) => {
				if (valid) {
					let { status, msg, data } = await Admin.login({ ...this.form });
					if (status) {
						//缓存数据
						sessionStorage.user_id = data.user_id;
						sessionStorage.role_id = data.role_id;
						sessionStorage.access_token = data.access_token;
						sessionStorage.refresh_token = data.refresh_token;
						global.is_route_unload = true;
						//信息提示
						this.$message.success(msg);
						// 获取重定向参数
						let { redirect } = this.$route.query;
						if (redirect) {
							// 重定向
							this.$router.push(redirect);
						} else {
							//跳转页面
							this.$router.push('/article/list');
						}

					} else {
						//信息提示
						this.$message.error(msg);
					}
				}
			});
		}
	}
}
</script>

<style lang="less" scoped>
.bg {
	width: 100vw;
	height: 100vh;
	background: url(./img/login-bg.jpg) center no-repeat;
	background-size: cover;
	position: relative;

	.box-card {
		position: fixed;
		right: 30px;
		top: 50%;
		transform: translateY(-50%);
		width: 400px;

		.forget {
			position: absolute;
			right: 20px;
		}
	}
}
</style>
